package com.zhiwei.codesecurity.web.api.taskadd.controller;

import com.mysql.jdbc.StringUtils;
import com.zhiwei.codesecurity.common.base.ServiceResponse;
import com.zhiwei.codesecurity.common.enums.UploadType;
import com.zhiwei.codesecurity.common.utils.BeanUtil;
import com.zhiwei.codesecurity.common.utils.FileUtils;
import com.zhiwei.codesecurity.common.utils.IdMaker;
import com.zhiwei.codesecurity.service.taskadd.ITaskAddService;
import com.zhiwei.codesecurity.service.taskadd.request.TaskAddReq;
import com.zhiwei.codesecurity.service.taskadd.response.TaskAddRlt;
import com.zhiwei.codesecurity.service.taskadd.response.TeamDetailServRlt;
import com.zhiwei.codesecurity.web.api.taskadd.request.CreateTaskReq;
import com.zhiwei.codesecurity.web.api.taskadd.response.UploadFileResp;
import com.zhiwei.codesecurity.web.common.base.BaseController;
import com.zhiwei.codesecurity.web.common.base.BaseResponse;
import com.zhiwei.codesecurity.web.common.base.RequestHead;
import com.zhiwei.codesecurity.common.constants.ResourcesPropertiesConstants;
import com.zhiwei.codesecurity.web.common.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/taskAdd")
public class TaskAddController extends BaseController {
    private static final String UPLOAD_DIR = ResourcesPropertiesConstants.TEMP_DIR;

    @Autowired
    @Qualifier("taskAddService")
    private ITaskAddService taskAddService;

    /**
     * 团队设置
     * @param head
     * @param result
     * @return
     */
    @RequestMapping(value = "/teamSetting", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse teamSetting (@RequestBody RequestHead head, BindingResult result) {
        logger.info(">>> process: 团队设置|accessToken={}", head.getAccessToken());
        if (ResponseUtil.existsParamsError(result)) {
            return ResponseUtil.getErrorParams(result);
        }

        ServiceResponse<TeamDetailServRlt> response = taskAddService.getTeamSetting();
        if (response.isError()) {
            logger.warn("团队设置, returnCode={}, returnMsg={}", response.getCode(), response.getMsg());
            return ResponseUtil.getErrorBusi(response.getMsg());
        }

        return ResponseUtil.getSuccessResponse(response.getData());
    }

    /**
     *  上传代码文件zip压缩包
     * @param accesstoken 用户令牌
     * @param uploadFile  代码文件zip
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse uploadfile(@RequestParam("accesstoken") String accesstoken, @RequestParam("uploadFile") CommonsMultipartFile uploadFile,
                                   HttpServletRequest request) {
        logger.info(">>> process:上传代码zip文件|accesstoken={}", accesstoken);
        if (StringUtils.isNullOrEmpty(accesstoken)) {
            logger.error("#### 用户令牌为空, {}", accesstoken);
            return ResponseUtil.getErrorBusi("用户令牌为空！");
        }

        if (null == uploadFile || uploadFile.isEmpty()) {
            logger.error("#### 上传代码文件为空, {}", uploadFile);
            return ResponseUtil.getErrorBusi("上传代码文件为空!");
        }

        // 获取带扩展名的文件名
        String originFileName = uploadFile.getOriginalFilename();
        logger.info(">>> process:获取带扩展名的文件名|originFileName={}", originFileName);

        // 获取文件扩展名
        String extension = originFileName.substring(originFileName.lastIndexOf("."));
        logger.info(">>> process:获取文件扩展名|extension={}", extension);
        if (!extension.toLowerCase().equals(".zip")) {
            logger.error("#### 上传文件类型错误, {}", extension);
            return ResponseUtil.getErrorBusi("上传文件类型错误！");
        }

        // 获取文件大小
        long filesize = uploadFile.getSize();
        logger.info(">>> process:获取文件大小|filesize={}", filesize);

        // 构造文件上传后的文件绝对路径
        String fileName = IdMaker.generate() + extension;
        String absFileName = UPLOAD_DIR + fileName;
        logger.info(">>> process:构造文件上传后的文件绝对路径|absFileName={}", absFileName);
        try {
            uploadFile.transferTo(new File(absFileName));
        } catch (IOException ex) {
            logger.error("#### 保存文件出错, {}", ex.toString());
            return ResponseUtil.getErrorBusi(ex.toString());
        }

        UploadFileResp uploadFileResp = new UploadFileResp();
        uploadFileResp.setFileName(fileName);

        return ResponseUtil.getSuccessResponse(uploadFileResp);
    }

    /**
     * 创建任务
     * @param head
     * @param createTaskReq
     * @param result
     * @return
     */
    @RequestMapping("/createTask")
    @ResponseBody
    public BaseResponse createTask(@RequestBody RequestHead head, @Valid @RequestBody CreateTaskReq createTaskReq,
                                   BindingResult result) {
        logger.info(">>> process: 创建任务|createTaskReq={}", createTaskReq);
        if (ResponseUtil.existsParamsError(result)) {
            return ResponseUtil.getErrorParams(result);
        }

        if (UploadType.LOCAL_UPLOAD.getKey().intValue() == createTaskReq.getUploadType().intValue()) {
            String fileAddress = UPLOAD_DIR + createTaskReq.getFileName();
            if (!FileUtils.isFileExist(fileAddress)) {
                return ResponseUtil.getErrorBusi("找不到上传的扫描文件!");
            }
        }

        TaskAddReq taskAddReq = new TaskAddReq();
        BeanUtil.copyPropertiesQuietly(createTaskReq, taskAddReq);
        taskAddReq.setCreatorId(head.getUserId());
        ServiceResponse<TaskAddRlt> response = taskAddService.taskAdd(taskAddReq);

        return ResponseUtil.getSuccessResponse(response.getData());
    }

}
